<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket群发或单发消息</title>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">浏览器不支持websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv" style="float: left;width: 45%;border: dot-dash;border-width: 2px;display: none">
        <form id="frm" method="post">
            <label>发送订阅消息</label><br/>
            登 录 名 : <input type="text" id="user" name="user" value="admin" style="width:200px;"/>
            外部消息编号 : <input type="text" id="refId" name="refId" value="11111111111111" style="width:220px;"/>
            <br>
            登录token:<textarea id="token" style="width:500px;height: 70px">eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXJyZW50VGltZU1pbGxpcyI6IjE2MDEzNDgyODE1NDEiLCJleHAiOjE2MDEzOTE0ODEsImFjY291bnQiOiJhZG1pbiJ9.YcQ94RBGtIBz4lK11e91tY1oD1pOIA6-FRW07XzQbSo</textarea>
            <br>
            目标用户（群发时目标用户无作用）:<input type="text" id="userCode" name="userCode" style="width: 100px"/>
            消息类别：<select id="category" name="category">
            <option value="WORK_ORDER" selected="true">工单</option>
        </select>

            单/群发：<select id="type" name="type">
            <option value="SINGLE" selected="true">单发</option>
            <option value="ALL">群发</option>
        </select><br/>
            Json消息:<textarea id="msg" name="msg" style="width:510px;"></textarea><br>
        </form>
        <button id="sendName" onclick=" send();">发送</button>
    </div>
    <div style="float: right;width: 50%;border: dot-dash;border-width: 2px;">
        <div id="resp1" style="border-width: 1px;border-color: red">
        </div>
        <hr>
        <div id="resp2" style="border-width: 1px;border-color: red">
        </div>
    </div>
</div>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery.serializeJSON/2.8.1/jquery.serializejson.js"></script>
<script type="application/javascript">
    let stompClient = null;
    let user = "";
    let token = "";
    const serverEndpoint = "http://192.168.150.63:8080/ws";

    function setConnected(connected) {
        $("#connect").attr("disabled", connected);
        $("#disconnect").attr("disabled", !connected);
        if (connected) {
            $("#conversationDiv").show();
        } else {
            $("#conversationDiv").hide();
        }
    }


    function connect() {
        user = $("#user").val();
        token = $("#token").html();
        const socket = new SockJS(serverEndpoint);
        stompClient = Stomp.over(socket);
        stompClient.debug = function (str) {
            console.log("DEBUG---->" + str);
        };
        // Add the following if you need automatic reconnect (delay is in milli seconds)
        stompClient.reconnect_delay = 5000;
        // client will send heartbeats every 5000ms
        stompClient.heartbeat.outgoing = 5000;
        // 0  client does not want to receive heartbeats from the server
        stompClient.heartbeat.incoming = 5000;

        // client.connect(headers, connectCallback);
        // client.connect(headers, connectCallback, errorCallback);
        // client.connect(headers, connectCallback, errorCallback, closeEventCallback);

        stompClient.connect({"Authorization": token}, function (frame) {
            setConnected(stompClient.connected);
            console.log("connect.....");
            // stompClient.subscribe('/topic/ws/broadcast', function (resp) {
            //     $("#resp1").append("<p>" + resp.body + "</p>")
            //     resp.ack({
            //         "MESSAGE_ID": resp.headers.MESSAGE_ID,
            //         "MESSAGE_TYPE": resp.headers.MESSAGE_TYPE,
            //         "MESSAGE_TRACE_ID": resp.headers.MESSAGE_TRACE_ID
            //     });
            // }, {ack: 'client'});

            // stompClient.subscribe('/user/' + user + '/reply', function (resp) {
            //     stompClient.send("/topic/message/receipt", {"Authorization": token}, JSON.stringify({
            //         'messageId': resp.headers.MESSAGE_ID,
            //         'traceId': resp.headers.MESSAGE_TRACE_ID,
            //         'messageType': resp.headers.MESSAGE_TYPE
            //     }));
            //     $("#resp2").append("<p>" + resp.body + "</p>");
            // });

            // stompClient.subscribe('/user/' + user + '/reply', function (resp) {
            //     $("#resp2").append("<p>" + resp.body + "</p>");
            //     resp.ack({
            //         "MESSAGE_ID": resp.headers.MESSAGE_ID,
            //         "MESSAGE_TYPE": resp.headers.MESSAGE_TYPE,
            //         "MESSAGE_TRACE_ID": resp.headers.MESSAGE_TRACE_ID
            //     });
            // }, {ack: 'client'});
        }, function (resp) {
            alert("网络已经断开" + resp)
            console.log("error:" + resp);
        });
    }

    function send() {
        if (stompClient.connected) {
            alert("已经连接")
            return;
        }
        alert("连接已经关闭")
    }


    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendMsg() {
        var frm = $('#frm').serializeJSON();
        var param = JSON.stringify(frm);
        $.ajax({
            type: 'POST',
            url: "/message/send",
            contentType: 'application/json',
            crossDomain: true,// 开启跨域支持
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", $("#token").html());
            },
            data: param,
            dataType: 'json',
            success: function (rec) {
                console.log(rec)
            }
        });
    }

    // function debounce(func, wait) {
    //     let timer;
    //     return function () {
    //         let context = this; // 注意 this 指向
    //         let args = arguments; // arguments中存着e
    //         if (timer) clearTimeout(timer);
    //         timer = setTimeout(() => {
    //             func.apply(this, args)
    //         }, wait)
    //     }
    // }
    //
    // function search() {
    //     console.log("可以执⾏你啦")
    // }
    //
    // document.addEventListener("scroll", debounce(search, 500))
    //document.getElementById('input-serach').addEventListener('input',debounce(search,500)

</script>
</body>
</html>